<template>
    <div class="order-management">
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-input
          v-model="searchForm.startDate"
          type="date"
          placeholder="输入开始日"
          style="width: 180px; margin-right: 10px;"
        />
        <el-input
          v-model="searchForm.endDate"
          type="date"
          placeholder="输入截止日"
          style="width: 180px; margin-right: 10px;"
        />
        <el-select v-model="searchForm.status" placeholder="选择订单状态" clearable style="width: 180px; margin-right: 10px;">
          <el-option label="待支付" value="待支付"/>
          <el-option label="已支付" value="已支付"/>
          <el-option label="已取消" value="已取消"/>
        </el-select>
      </div>
      <!-- 关键字搜索 -->
      <el-input
        v-model="searchForm.keyword"
        placeholder="请输入订单号、联系人或客户昵称"
        clearable
        style="width: 300px; float: right; margin-bottom: 20px;"
        @clear="handleSearch"
        @keyup.enter.native="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"/>
      </el-input>
      <!-- 订单列表 -->
      <el-table :data="tableData" border style="width: 100%; margin-top: 20px;">
        <el-table-column prop="productName" label="产品名称"/>
        <el-table-column prop="orderAmount" label="订单金额"/>
        <el-table-column prop="paymentMethod" label="付款方式"/>
        <el-table-column prop="orderStatus" label="订单状态"/>
        <el-table-column prop="orderSource" label="订单来源"/>
        <el-table-column prop="contactPerson" label="联系人"/>
        <el-table-column prop="contactPhone" label="联系电话"/>
        <el-table-column prop="customerName" label="客户昵称"/>
        <el-table-column prop="orderTime" label="下单时间">
          <template slot-scope="scope">
            {{ scope.row.orderTime ? new Date(scope.row.orderTime).toLocaleString() : '' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="text" @click="handleView(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination"
      />
      <el-dialog title="编辑订单" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="产品名称">
          <el-input v-model="editForm.productName"></el-input>
        </el-form-item>
        <el-form-item label="订单金额">
          <el-input v-model="editForm.orderAmount" type="number"></el-input>
        </el-form-item>
        <el-form-item label="付款方式">
          <el-select v-model="editForm.paymentMethod" placeholder="请选择付款方式">
            <el-option label="微信支付" value="微信支付"></el-option>
            <el-option label="支付宝" value="支付宝"></el-option>
            <el-option label="银行转账" value="银行转账"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开启退款通道">
          <el-select v-model="editForm.orderStatus" placeholder="开启退款通道">
            <el-option label="已关闭" value="已支付"></el-option>
            <el-option label="已开启" value="待退款"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单来源">
          <el-input v-model="editForm.orderSource"></el-input>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="editForm.contactPerson"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="editForm.contactPhone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确定</el-button>
      </span>
    </el-dialog>

    </div>
  </template>

  <script>
  import axios from '@/utils/request'
  
  export default {
    name: 'OrderManagement',
    data() {
      return {
        searchForm: {
          startDate: '',
          endDate: '',
          status: '',
          keyword: ''  // 添加关键字搜索
        },
        tableData: [],
        currentPage: 1,
        pageSize: 10,
        total: 0,
        editDialogVisible: false,
        editForm: {
          id: '',
          productName: '',
          orderAmount: '',
          paymentMethod: '',
          orderStatus: '',
          orderSource: '',
          contactPerson: '',
          contactPhone: ''
        }
      }
    },
    methods: {
      async fetchData() {
        try {
          const params = {
            page: this.currentPage,
            pageSize: this.pageSize
          }
  
          // 关键字搜索 - 支持联系人、订单号、客户昵称
          if (this.searchForm.keyword && this.searchForm.keyword.trim()) {
            const keyword = this.searchForm.keyword.trim()
            params.keyword = keyword
            // 移除额外的参数设置，让后端统一处理关键字搜索
          }
          
          // 订单状态
          if (this.searchForm.status) {
            params.status = this.searchForm.status
          }
  
          // 日期查询
          if (this.searchForm.startDate) {
            params.beginTime = this.searchForm.startDate + ' 00:00:00'
          }
          if (this.searchForm.endDate) {
            params.endTime = this.searchForm.endDate + ' 23:59:59'
          }
  
          console.log('发送请求参数：', params)
          const res = await axios.get('/admin/order/page', { params })
          console.log('完整响应数据：', res)
  
          // 检查响应数据结构
          if (res.code === 1 && res.data && res.data.records) {
            // 处理日期格式
            this.tableData = res.data.records.map(record => ({
              ...record,
              orderTime: record.orderTime ? new Date(record.orderTime).toLocaleString() : '',
              createTime: record.createTime ? new Date(record.createTime).toLocaleString() : '',
              updateTime: record.updateTime ? new Date(record.updateTime).toLocaleString() : ''
            }))
            this.total = res.data.total || 0
            
            // 如果搜索结果为空，显示提示
            if (this.tableData.length === 0) {
              this.$message.info('未找到匹配的数据')
            }
          } else {
            this.tableData = []
            this.total = 0
            this.$message.warning(res.msg || '获取数据失败')
          }
        } catch (error) {
          console.error('获取订单数据失败：', error)
          this.$message.error('获取数据失败：' + (error.message || '未知错误'))
          this.tableData = []
          this.total = 0
        }
      },
      handleSearch() {
        this.currentPage = 1
        this.fetchData()
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.fetchData()
      },

      handleView(row) {
        this.editForm = { ...row }
        this.editDialogVisible = true
      },

      // 提交编辑
      async handleEditSubmit() {
        try {
          const res = await axios.put(`/admin/order/${this.editForm.id}`, {
            id: this.editForm.id,
            productName: this.editForm.productName,
            orderAmount: this.editForm.orderAmount,
            paymentMethod: this.editForm.paymentMethod,
            orderStatus: this.editForm.orderStatus,
            orderSource: this.editForm.orderSource,
            contactPerson: this.editForm.contactPerson,
            contactPhone: this.editForm.contactPhone
          })
          
          if (res.code === 1) {
            this.$message.success('更新成功')
            this.editDialogVisible = false
            this.fetchData() // 刷新列表
          } else {
            this.$message.error(res.msg || '更新失败')
          }
        } catch (error) {
          console.error('更新订单失败：', error)
          this.$message.error('更新失败')
        }
      }

    },
    created() {
      this.fetchData()
    },
    watch: {
      'searchForm.status': {
        handler() {
          this.handleSearch()
        }
      }
    },
  }
  </script>
  
  <style scoped>
  .order-management {
    padding: 20px;
  }
  
  .search-area {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  </style>